//138. 复制带随机指针的链表

#include <stdlib.h>
struct Node {
	int val;
	struct Node* next;
	struct Node* random;
};
struct Node* copyRandomList(struct Node* head) {
    //1.拷贝节点插在原结点后面
    struct Node* cur = head;
    while (cur)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;//拷贝结点值
        //连接
        struct Node* next = cur->next;//next变量可以令下面连接两步的顺序改变而不出错
        copy->next = next;
        cur->next = copy;
        //迭代
        cur = next;
    }
    //2.控制拷贝结点的random
    cur = head;
    while (cur)
    {
        struct Node* copy = cur->next;
        if (cur->random == NULL)//考虑cur->random指向NULL的情况
            copy->random = NULL;
        else
            copy->random = cur->random->next;
        //迭代
        cur = copy->next;
    }
    //3.拷贝的结点解下来，尾插组成拷贝链表
    struct Node* copyHead = NULL, * copyTail = NULL;
    cur = head;
    while (cur)
    {
        struct Node* copy = cur->next;
        //struct Node* next = copy->next;
        //尾插
        if (copyTail == NULL)
        {
            copyHead = copyTail = copy;
        }
        else
        {
            copyTail->next = copy;
            copyTail = copyTail->next;
        }
        //恢复原链表
        //cur->next = next;
        cur->next = copy->next;
        //迭代
        //cur = next;
        cur = copy->next;
    }

    return copyHead;
}